import axios from 'axios'
import { getToken } from '@/utils/auth'

export function download(url, params, headers, name) {
  axios.get(url,
    {
      params: params,
      headers: headers,
      responseType: 'blob'
    }).then(res => {
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    window.URL.revokeObjectURL(url)
  })
}

export function downloadAtt(url, params, headers, name) {
  headers['x-token'] = getToken()
  axios.get(url,
    {
      params: params,
      headers: headers,
      responseType: 'blob'
    }).then(res => {
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    window.URL.revokeObjectURL(url)
  })
}

export function downloadFile(id, name) {
  const headers = { 'x-token': getToken() }
  axios.get('/api/sysFile/download',
    {
      params: {
        'id': id
      },
      headers: headers,
      responseType: 'blob'
    }).then(res => {
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    window.URL.revokeObjectURL(url)
  })
}

export function downloadTemplate(url, params, headers, name) {
  headers['x-token'] = getToken()
  axios.get('/api/' + url + '/template',
    {
      params: params,
      headers: headers,
      responseType: 'blob'
    }).then(res => {
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    window.URL.revokeObjectURL(url)
  })
}
